import type { App, DirectiveBinding } from "vue";
 /**
   * @param event 事件类型 默认click
   * @param handler 回调函数
   * @param delay 时间阈值 单位ms
   * 包成对象
   */
interface DebounceDirectiveArgs {
  event?: string;
  delay?: number;
  handler: () => void;
}
const defaultArgs: DebounceDirectiveArgs = {
  event: "click",
  delay: 300,
  handler: () => {
    console.log("default handler");
  },
};
export default function (app: App): void {
  app.directive("debounce", {
    mounted(
      el: HTMLElement,
      binding: DirectiveBinding<DebounceDirectiveArgs>
    ): void {
      let timer: number | null = null;
      const args = {
        ...defaultArgs,
        ...binding.value,
      };
      el.addEventListener(args.event!, () => {
        clearTimeout(timer as number);
        timer = setTimeout(() => {
          args.handler();
        }, args.delay!);
      });
    },
  });
}
